const express = require('express')
const router = express.Router()
const logger = require('../utils/logger')
const { scanCourses, getLessonsForCourse } = require('../utils/resourceScanner')

// Get all courses
router.get('/', async (req, res) => {
  try {
    const courses = await scanCourses()
    res.json(courses)
  } catch (error) {
    logger.error(error)
    res.status(500).json({ message: 'Error fetching courses', error: error.message })
  }
})

// Get course by ID
router.get('/:id', async (req, res) => {
  try {
    const courses = await scanCourses()
    let course = {}
    courses.find((c) => {
      for (let i = 0; i < c.courses.length; i++) {
        if (c.courses[i].id == req.params.id) {
          course = c.courses[i]
          return true
        }
      }
      return false
    })
    if (!course) {
      return res.status(404).json({ message: 'Course not found' })
    }
    res.json(course)
  } catch (error) {
    logger.error(error)
    res.status(500).json({ message: 'Error fetching course', error: error.message })
  }
})

// Get lessons for a course
router.get('/:courseId/lessons', async (req, res) => {
  try {
    // First find the course by ID to get its path
    const courses = await scanCourses()
    let course = {}
    courses.find((c) => {
      for (let i = 0; i < c.courses.length; i++) {
        if (c.courses[i].id == req.params.courseId) {
          course = c.courses[i]
          return true
        }
      }
      return false
    })
    if (!course) {
      console.error(`Course ${req.params.courseId} not found`)
      return res.status(404).json({ message: 'Course not found' })
    }

    // Then get lessons using the course path
    const lessons = await getLessonsForCourse(course.path)
    res.json(lessons)
  } catch (error) {
    logger.error(error)
    res.status(500).json({ message: 'Error fetching lessons', error: error.message })
  }
})

module.exports = router
